package org.wlw.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloServlet extends HttpServlet {

    /**
     * init方法只会在servlet创建的时候执行一次，用来进行初始化操作
     * */
    @Override
    public void init() throws ServletException {
        System.out.println("servlet init!!!!!!!!!!!!!!!!");
    }

    /**
     * 会执行一次
     * */
    @Override
    public void destroy() {
        System.out.println("servlet destory");
    }

    /*
    * service是一个共同的方法，不论是get请求还是post请求，最终都会执行这个service
    * */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        System.out.println("service is running");
    }

    //执行GET请求的方法
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doGet is running");
        req.setCharacterEncoding("UTF-8");//让请求的参数编码为utf-8
        String age = req.getParameter("age");
        String username = req.getParameter("username");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.println("<h1>hello servlet</h1>");
        out.println("<h2>"+age+"</h2>");
        out.println("<h2>"+username+"</h2>");
    }

    //执行post请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
